import { useEffect } from 'react'

/**
 * 根据图片宽度动态设置容器font-size，实现内容自适应缩放
 * @param imgRef 图片img元素的ref
 * @param containerRef 需要设置font-size的容器ref
 * @param ratio 字体缩放系数
 */
export function useResponsiveFontSize(
  imgRef: React.RefObject<HTMLElement>,
  containerRef: React.RefObject<HTMLElement>,
  ratio: number
) {
  useEffect(() => {
    const setFontSize = () => {
      if (imgRef.current && containerRef.current) {
        const width = (imgRef.current as HTMLElement).clientWidth
        containerRef.current.style.fontSize = `${width * ratio}px`
      }
    }
    setFontSize()
    let resizeObserver: ResizeObserver | null = null
    if (imgRef.current) {
      resizeObserver = new ResizeObserver(setFontSize)
      resizeObserver.observe(imgRef.current)
    }
    window.addEventListener('resize', setFontSize)
    return () => {
      if (resizeObserver && imgRef.current) resizeObserver.disconnect()
      window.removeEventListener('resize', setFontSize)
    }
  }, [imgRef, containerRef, ratio])
}
